// pages/order/submitOrder.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const app = getApp()
let ServiceUrl = app.globalData.ServiceUrl;
Page({

  /**
   * 页面的初始数据
   */
  data: {
      order_sn: '',//订单号
      oldman_name: '',//就诊对象
      to_name: '',
      service_type: '',
      require_time:'',//出发时间
      start_name: '',
      require_transport: '',//出行方式
      distance: '',
      isSpecify: '否',
      require_fee:'',
      extra_fee:'',
      code_string:'请扫码添加代金券',//代金券信息
      show: false
  },
  //使用代金券
  qrcode: function(){
    console.log('使用代金券')
    let that = this
    wx.scanCode({        //扫描API
      success: function(codeInfo){
        console.log(codeInfo);    //输出回调信息
        if(codeInfo){
          //检查代金券是否有效
          wx.request({
            url: ServiceUrl + 'checkCode',
            data: {
              code_string: codeInfo.result,
              order_id: that.data.order_id,
              user_id: that.data.user_id
            },
            method: 'post',
            success: function(res){
              console.log(res)
              if(res.data.state == 200){
                wx.showToast({
                  title: res.data.msg,
                  duration: 2000
                })
                that.setData({
                  code_string: codeInfo.result,
                  pay_fee: '0.0'
                });
              }else{
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            },
            fail: function(){
              console.log('发送请求失败')
            }
          })
        }
      }
    })

  },
  //付款方式
  payOrderAccompany:function(){
    let that = this
    console.log(that.data.user_id)
    console.log(that.data.code_string)
    let order_id = that.data.order_id
    let code_string = that.data.code_string
    //选择使用微信付款还是代金券
    if(that.data.pay_fee == '0.0'){
      console.log('代金券支付')
      that.codePay(order_id, code_string)
    }else{
      console.log('微信支付')
      that.wxPay(order_id)
    }
  },
  //使用代金券支付
  codePay: function(order_id, code_string){
    let that = this
    wx.request({
      url: ServiceUrl + 'codePay',
      data: {
        order_id: order_id,
        user_id: that.data.user_id,
        code_string: code_string
      },
      method: 'get',
      success: function(res){
        console.log(res)
        if(res.data.state == 200){
          //给管理员发送订单通知消息
          wx.request({
            url: ServiceUrl + 'sendLeaderMsg',
            data: {order_id: order_id},
            method: "get",
            success: function(res){
              console.log(res)
            }
          })
          wx.showToast({
            title: res.data.msg,
          })
          //跳转订单详情界面
          setTimeout(() => {
            wx.redirectTo({
              url: res.data.url,
            })  
          }, 2500);
          
        }else{
          wx.showToast({
            title: res.data.msg,
          })
        }
      },
      fail: function(){
        console.log('发送请求失败')
      }
    })
  },
  //使用微信支付
  wxPay:function(order_id){
    let that = this
    wx.request({
      url: ServiceUrl + 'payOrderAccompany',
      data: {order_id: order_id},
      method: "post",
      success: function(res){
        console.log(res)
        wx.requestPayment({
          nonceStr: res.data.nonceStr,//随机串
          package: res.data.package,
          paySign: res.data.paySign,//微信签名
          timeStamp: res.data.timeStamp,//时间戳，自1970年以来的秒数
          signType:'MD5',//微信签名方式
          success: function(res){
            console.log(res);
            that.setData({
              newState:3
            })
            //给管理员发送订单通知消息
            wx.request({
              url: ServiceUrl + 'sendLeaderMsg',
              data: {order_id: order_id},
              method: "get",
              success: function(res){
                console.log(res)
              }
            })
            //修改订单状态
            wx.request({
              url: ServiceUrl + 'payOrderAccompanyEnd',
              data:{order_id: order_id},
              method: 'post',
              success:function(res){
                console.log(res)
                if(res.data.state == 200){
                  console.log(res.data.msg)
                  wx.showModal({
                    title:"提示",
                    content:"支付成功,将尽快为您安排服务！",
                    showCancel: false,
                    confirmColor: 'skyblue',
                    success: function(){
                      setTimeout(() => {
                        wx.navigateTo({
                          url: '../details/accompany?order_id='+that.data.order_id,
                        })
                      }, 2000);
                    }
                  })
                }else{
                  console.log(res.data.msg)
                }
              },
              fail:function(res){
                wx.showModal({
                  title:"提示",
                  content:"订单状态修改失败",
                  showCancel: false,
                  confirmColor: 'skyblue',
                })
              }
            })
          },
          // fail:function(res){
          //   wx.showModal({
          //     title:"提示",
          //     content:"调起支付失败",
          //     showCancel:false
          //   })
          // }
        })
      },
      error:function(){
        console.log('发送请求失败')
      }
    })
  },
  //计算规则  
  rules:function(){
    Dialog.alert({
      title: '计算规则',
      message: '陪诊服务费用（5公里内）为120.0元，超过5公里，每5公里加收20元。（不足5公里按5公里计算）',
    }).then(() => {
      // on close
    });
  },
  watchDetails:function(){
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    console.log(options)
    if(wx.getStorageSync('uid') == '' || wx.getStorageSync('uid') == 'undefined'){
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.redirectTo({
          url: '../index/index',
        })
      }, 2000);
    }
    let user_id = wx.getStorageSync('uid') ? wx.getStorageSync('uid') : options.user_id
    if(options.order_id != '' || options.order_id != 'none' || options.order_id != 'unde'){
      that.orderInfo(options.order_id)
      that.setData({
        order_id:options.order_id,
        user_id: user_id
      })
    }else{
      wx.redirectTo({
        url: '../index/index',
      })
    }
  },
orderInfo:function(order_id){
  let that = this
  wx.request({
    url: ServiceUrl + 'getOrderInfo',
    data: {order_id: order_id},
//    data: {order_id: 5},
    success: function(res){
      console.log(res.data)
      if(res.data.state == 200){
        that.setData({
          order_sn: res.data.data.order_sn,
          oldman_name: res.data.data.oldman_name,
          to_name: res.data.data.to_name,
          service_type: res.data.data.service_type,
          require_time: res.data.data.require_date+' '+res.data.data.require_time,
          start_name: res.data.data.start_name,
          require_transport: res.data.data.require_transport,
          distance: res.data.data.distance,
          require_fee: res.data.data.require_fee,
          extra_fee: res.data.data.extra_fee,
          pay_fee: res.data.data.pay_fee
        })
      }
    },
    error: function(res){
      console.log('发送请求失败')
    }
  })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that = this
    setTimeout(() => {
      wx.stopPullDownRefresh({
        success: (res) => {
          that.orderInfo(that.data.order_id)
        },
      })
    }, 3000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})